<template>
  <div id="app">
    <h1>数据看版</h1>
    <div v-if="loading">Loading...</div>
    <div v-else-if="error" class="error-message">
      <p>Failed to load data: {{ error }}</p>
      <button @click="fetchData">Retry</button>
    </div>
    <div v-else-if="data.length === 0" class="empty-message">
      <p>No data found</p>
    </div>
  <div v-else>
    <div v-if="!selectedDevice">
      <div class="filters">
        <input 
          v-model="filterModel" 
          placeholder="Search by model..."
          class="filter-input"
        >
        <select v-model="filterGrade" class="filter-select">
          <option value="">All Grades</option>
          <option v-for="grade in availableGrades" :key="grade" :value="grade">{{ grade }}</option>
        </select>
        <select v-model="filterBrand" class="filter-brand">
          <option value="">All Brands</option>
          <option v-for="brand in availableBrands" :key="brand" :value="brand">{{ brand }}</option>
        </select>
      </div>
      <div class="device-list">
      <div v-for="(device, index) in filteredData" :key="index" class="device-card" @click="selectDevice(device)">
        <h3>{{ device.brand }} {{ device.model }}</h3>
        <div class="device-details">
          <p><strong>颜色:</strong> {{ device.color }}</p>
          <p><strong>品牌:</strong> {{ device.brand }}</p>
          <p><strong>内存:</strong> {{ device.ram || '未知' }}</p>
          <p><strong>存储:</strong> {{ device.storage }}</p>
          <p><strong>价格:</strong> ¥{{ device.upset_price }}</p>
          <p><strong>等级:</strong> {{ device.grade }}</p>
        </div>
      </div>
    </div>
    </div>
    <div v-else class="device-detail">
      <button @click="selectedDevice = null" class="back-button">← 返回列表</button>
      <h2>{{ selectedDevice.brand }} {{ selectedDevice.model }}</h2>
      <div class="detail-content">
        <p><strong>颜色:</strong> {{ selectedDevice.color }}</p>
        <p><strong>品牌:</strong> {{ selectedDevice.brand }}</p>
        <p><strong>内存:</strong> {{ selectedDevice.ram || '未知' }}</p>
        <p><strong>存储:</strong> {{ selectedDevice.storage }}</p>
        <p><strong>价格:</strong> ¥{{ selectedDevice.upset_price }}</p>
        <p><strong>等级:</strong> {{ selectedDevice.grade }}</p>
        <div v-if="selectedDevice.quality_desc" class="quality-desc">
          <h3>质量描述:</h3>
          <ul>
            <li v-for="(desc, key) in selectedDevice.quality_desc" :key="key">
              {{ key }}: {{ desc }}
            </li>
          </ul>
        </div>
        <div v-if="selectedDevice.raw_defect_url" class="defect-images">
          <h3>缺陷图片:</h3>
          <div class="defects-container">
            <div v-for="(url, desc, index) in selectedDevice.raw_defect_url" 
                 :key="desc" 
                 class="defect-item"
                 @click="openLightbox(index)">
              <img 
                :src="url.split('|')[0].trim()" 
                :alt="desc"
                class="defect-image"
              >
              <p class="defect-desc">{{ desc }}</p>
            </div>
          </div>
        </div>

        <!-- Lightbox Modal -->
        <div v-if="showLightbox" class="lightbox" @click.self="closeLightbox">
          <button class="close-btn" @click="closeLightbox">×</button>
          <button class="nav-btn prev-btn" @click.stop="prevImage">←</button>
          <div class="lightbox-content">
            <img :src="currentImage.url" :alt="currentImage.desc">
            <p class="lightbox-desc">{{ currentImage.desc }}</p>
          </div>
          <button class="nav-btn next-btn" @click.stop="nextImage">→</button>
        </div>
      </div>
    </div>
    <div v-if="!selectedDevice" class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">Previous</button>
      <span>Page {{ currentPage }}</span>
      <button @click="nextPage">Next</button>
      <div class="page-jump">
        <input 
          type="number" 
          v-model.number="jumpPage" 
          min="1" 
          placeholder="Page"
          @keyup.enter="goToPage"
        >
        <button @click="goToPage">Go</button>
      </div>
    </div>
  </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'App',
  data() {
    return {
      data: [],
      loading: true,
      currentPage: 1,
      selectedDevice: null,
      jumpPage: null,
      filterModel: '',
      filterGrade: '',
      filterBrand: '',
      showLightbox: false,
      currentImageIndex: 0,
      lightboxImages: [],
      currentImage: {}
    }
  },
  computed: {
    availableGrades() {
      const grades = new Set()
      this.data.forEach(device => {
        if (device.grade) {
          grades.add(device.grade)
        }
      })
      return Array.from(grades)
    },
    availableBrands() {
      const brands = new Set()
      this.data.forEach(device => {
        if (device.brand) {
          brands.add(device.brand)
        }
      })
      return Array.from(brands)
    },
    filteredData() {
      return this.data.filter(device => {
        const matchesModel = device.model.toLowerCase().includes(this.filterModel.toLowerCase())
        const matchesGrade = !this.filterGrade || device.grade === this.filterGrade
        const matchesBrand = !this.filterBrand || device.brand === this.filterBrand
        return matchesModel && matchesGrade && matchesBrand
      })
    }
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const response = await axios.get(`/api/spider/${this.currentPage}`)
        console.log('API Response:', response) // 输出完整响应对象
        // 尝试不同方式解析响应数据
        let responseData = response.data;
        if (typeof responseData === 'string') {
          try {
            responseData = JSON.parse(responseData);
          } catch (e) {
            console.error('JSON parse error:', e);
          }
        }
        
        // 处理可能的响应格式
        this.data = Array.isArray(responseData) ? responseData :
                   responseData?.list || 
                   responseData?.data || 
                   [];
        
        console.log('Processed data:', this.data); // 输出处理后的数据
      } catch (error) {
        console.error('Error fetching data:', error)
        this.error = error.message || 'Failed to load data'
        this.data = []
      } finally {
        this.loading = false
      }
    },
    nextPage() {
      this.currentPage++
      this.fetchData()
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.fetchData()
      }
    },
    selectDevice(device) {
      this.selectedDevice = device
      if (device.raw_defect_url) {
        this.lightboxImages = []
        Object.entries(device.raw_defect_url).forEach(([desc, url]) => {
          // Handle URLs with multiple images separated by |
          const urls = url.split('|').map(u => u.trim())
          if (urls.length > 1) {
            urls.forEach((u, i) => {
              this.lightboxImages.push({ 
                desc: `${desc} (${i+1}/${urls.length})`, 
                url: u 
              })
            })
          } else {
            this.lightboxImages.push({ desc, url })
          }
        })
      }
    },
    openLightbox(index) {
      this.currentImageIndex = index
      this.currentImage = this.lightboxImages[index]
      this.showLightbox = true
    },
    closeLightbox() {
      this.showLightbox = false
    },
    nextImage() {
      this.currentImageIndex = (this.currentImageIndex + 1) % this.lightboxImages.length
      this.currentImage = this.lightboxImages[this.currentImageIndex]
    },
    prevImage() {
      this.currentImageIndex = (this.currentImageIndex - 1 + this.lightboxImages.length) % this.lightboxImages.length
      this.currentImage = this.lightboxImages[this.currentImageIndex]
    },
    handleKeydown(e) {
      if (this.showLightbox) {
        if (e.key === 'ArrowRight') this.nextImage()
        if (e.key === 'ArrowLeft') this.prevImage()
        if (e.key === 'Escape') this.closeLightbox()
      }
    },
    goToPage() {
      if (this.jumpPage && this.jumpPage > 0) {
        this.currentPage = this.jumpPage
        this.fetchData()
        this.jumpPage = null
      }
    }
  },
  created() {
    this.fetchData()
    window.addEventListener('keydown', this.handleKeydown)
  },
  beforeUnmount() {
    window.removeEventListener('keydown', this.handleKeydown)
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.filters {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  justify-content: center;
}

.filter-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 200px;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 150px;
}
.filter-brand {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 250px;
}

.pagination {
  margin: 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.page-jump {
  display: flex;
  gap: 5px;
  margin-left: 20px;
}

.page-jump input {
  width: 60px;
  padding: 5px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  background: #42b983;
  color: yellow;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.device-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.device-card {
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: all 0.2s ease;
}

.device-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  background-color: #ffa500;
}

.device-details {
  margin-top: 10px;
}

.quality-desc {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.defect-images {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.defects-container {
  display: flex;
  overflow-x: auto;
  gap: 15px;
  padding: 10px 0;
}

.defect-item {
  flex: 0 0 auto;
  cursor: pointer;
  transition: transform 0.2s;
}

.defect-item:hover {
  transform: scale(1.02);
}

.defect-image {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.defect-desc {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
  max-width: 200px;
  text-align: center;
}

/* Lightbox Styles */
.lightbox {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.lightbox-content {
  max-width: 80vw;
  max-height: 80vh;
  text-align: center;
}

.lightbox-content img {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.lightbox-desc {
  color: white;
  margin-top: 10px;
  font-size: 16px;
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  background: none;
  border: none;
  color: white;
  font-size: 30px;
  cursor: pointer;
}

.nav-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.3);
  border: none;
  color: white;
  font-size: 30px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  transition: background 0.2s;
}

.nav-btn:hover {
  background: rgba(255, 255, 255, 0.5);
}

.prev-btn {
  left: 20px;
}

.next-btn {
  right: 20px;
}

.quality-desc ul {
  padding-left: 20px;
  margin: 5px 0;
}

.quality-desc li {
  margin-bottom: 5px;
  font-size: 14px;
}

.error-message {
  color: #ff4444;
  padding: 20px;
  text-align: center;
}

.error-message button {
  margin-top: 10px;
}

.empty-message {
  color: #666;
  padding: 20px;
  text-align: center;
  font-size: 18px;
}
</style>
